import * as types from '../constants/ActionTypes'
import * as API_ADDCUSTOMER from '../apis/addCustomer'

import {Modal,message} from 'antd'
import objectAssign from 'object-assign'

import cloneDeep from 'lodash/cloneDeep'

import {WeaTools,WeaDialog} from 'ecCom'
import Immutable from 'immutable'

//记录当前流程页
export const setNowRouterCmpath = value => {
	return {
		type: types.SET_NOW_ROUTER_PATH,
		path: value
	}
}


// export const saveParams = (value) => {
// 	return (dispatch, getState) => {
// 		const viewScope = getState().addcustomer.get('nowRouterCmpath');
// 		dispatch({
// 			type: types.SAVE_ADD_PARAMS,
// 			value: value
// 		})
// 	}
// }

//搜索表单内容
export const saveOrderFields = (value = {}) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		dispatch({
			type: viewScope + '_' + types.SAVE_ORDER_FIELDS,
			value: value
		})
	}
}

//切换tab
export const changeTabs = (params) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		dispatch({
			type: viewScope + '_' + types.SET_DETAIL_TABKEY,
			selectKey: params
		});
		if (params == "2") {
			dispatch(excelToDBInfo());  //获取批量导入基本信息)
			jQuery.ajax({
				url: "/api/crm/customer/generateExcel",
				type: "GET",
				dataType: "json",
				success: function (data) {}
			});
		}
	}
}

//客户类型查询
export const customerType = (params) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		API_ADDCUSTOMER.getCustomerType(params).then((data) => {
			if (data.status == "success") {
				dispatch({
					type: `${viewScope}_` + types.INIT_TYPE,
					customerTypeList: data.customerTypeList,
					defaultvalue: data.value,
				});
				dispatch(saveOrderFields({
					type: {
						name: "type",
						value: data.value
					}
				}));
			} else {
				message.error('请求失败,' + data.msgcode + "!");
			}
		});
	}
}
//获取批量导入的基本信息
export const excelToDBInfo = (params) => {
	return (dispatch, getState) => {
		API_ADDCUSTOMER.getCrmImportDatas(params).then((data) => {
			if (data.status == "success") {
				dispatch({
					type: types.ADD_INIT_IMPORTDATAS,
					importdatas: data.datas,
				});
				const datainfo = data.datas;
				dispatch(saveOrderFields({
					manager: {
						name: "manager",
						value: datainfo.manager.value
					},
					CustomerStatus: {
						name: "CustomerStatus",
						value: datainfo.customerStatus.value
					}
				}));
			} else {
				message.error('请求失败,' + data.msgcode + "!");
			}
		});
	}
}
//新建客户,搜索客户接口
export const myCustomerListForAdd = (params) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		const searchParamsAd = getState()["addcustomer"].get('searchParamsAd').toJS();
		const newParams = { ...params,
			...searchParamsAd
		};
		if (!searchParamsAd.name) {
			Modal.warning({
				title: '系统提示',
				content: '必要信息不完整，红色标记为必填项！',
			});
		} else {
			dispatch({
				type: viewScope + '_' + types.LOADING,
				loading: true
			});

			API_ADDCUSTOMER.getMyCustomerListForAdd(newParams).then((data) => {
				if (data.status == "success") {
					dispatch({
						type: types.ADDCUSTOMER_SEARCH,
						recordDatas: data.datas,
						tooManyRecord: data.tooManyRecord,
						noRecord: data.noRecord,
						loading: false
					});
					if (data.noRecord) { //加载新建form
						dispatch(searchCustomers());
					}
				} else {
					message.error('请求失败,' + data.msgcode + "!");
				}
			});
		}
	}
}

//新建客户查询
export const searchCustomers = (params) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		const searchParamsAd = getState()["addcustomer"].get('searchParamsAd').toJS();
		const newParams = { ...params,
			...searchParamsAd
		};

		dispatch({
			type: viewScope + '_' + types.LOADING,
			loading: true
		});

		API_ADDCUSTOMER.getCustomerAdd(newParams).then((data) => {
			if (data.status == "success") {
				dispatch({
					type: `${viewScope}_` + types.INIT_FORM,
					customerAddForm: data.datas,
					noRecord: true,
					loading: false
				});
			} else {
				message.error('请求失败,' + data.msgcode + "!");
			}
		});
	}
}

//新建客户保存
export const saveCustomers = (params) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		const searchParamsAd = getState()["addcustomer"].get('searchParamsAd').toJS();
		const requiredAttr = getState()["addcustomer"].get('requiredAttr').toJS();

		const newParams = { ...params,
			...searchParamsAd
		};
		const require = function () {
			let bool = true;
			for (let i = 0; i < requiredAttr.length; i++) {
				if (!searchParamsAd[requiredAttr[i]]) {
					bool = false;
				}
			}
			return bool;
		}();
		if(require){
			API_ADDCUSTOMER.getCustomerSave(newParams).then((data) => {
				if (data.status == "success") {
					message.success("保存成功!");
					weaHistory.push({
						pathname: '/main/crm/customerView?customerId=' + data.datas
					});
				} else {
					message.error('请求失败,' + data.msgcode + "!");
				}
			});
		}else{
			Modal.warning({
				title: '系统提示',
				content: '必要信息不完整，红色标记为必填项！',
			});
		}
	}
}

//保存必填字段
export const saveReqiuredAttr = (params) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		dispatch({
			type: viewScope + '_' + types.SAVE_REQUIRED,
			requiredAttr: params
		})
	}
}

//批量导入
export const startImportFile = (params) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		const searchParamsAd = getState()["addcustomer"].get('searchParamsAd').toJS();
		const newParams = { ...params,
			...searchParamsAd
		};
		dispatch({type: viewScope + '_' + types.LOADING,loading: true});
		
		API_ADDCUSTOMER.crmImport(newParams).then((data) => {
			dispatch({type: viewScope + '_' + types.LOADING,loading: false});
			if (data.status == "failed") {
				if (data.isErreData) {
					Modal.confirm({
						title: '系统提示',
						content: data.msg,
						onOk() {
							jQuery("#downFile").attr("src", `${"/weaver/weaver.crm.util.FileDownload?fileid="+data.fileid+"&filepath="+data.filepath}`);
						},
						onCancel() {
							API_ADDCUSTOMER.crmImport({"operation": "deleteFile","fileid": data.fileid}).then(data=>{
								return true;
							}).catch(err=>message.error(err))
						},
					});
					return;
				}else{
					Modal.error({
						title: '系统提示',
						content: data.msg,
					});
				}
			} else if (data.status == "success") {
				Modal.success({
					title: '系统提示',
					content: data.msg,
				});
			}
		});
	}
}

//组件卸载时需要清除的数据
export const unmountClear = (bool) => {
	return (dispatch, getState) => {
		const viewScope = getState().addcustomer.get('nowRouterCmpath');
		dispatch({
			type: viewScope + '_' + types.UNMOUNT_CLEAR,
			isToReq: true
		})
	}
}